<template>
  <div class="max-w-4xl mx-auto bg-white rounded-lg shadow-md overflow-hidden">
    <!-- 返回按钮 -->
    <div class="p-4 border-b border-gray-100">
      <router-link to="/" class="text-gray-500 hover:text-gray-700 flex items-center">
        <i class="fas fa-arrow-left mr-2"></i>
        <span>返回</span>
      </router-link>
    </div>
    
    <!-- 帖子内容 -->
    <div class="p-6">
      <div class="flex items-center">
        <UserAvatar :user="post.user" size="md" />
        
        <div class="ml-3">
          <div class="font-medium text-gray-900">
            <router-link :to="{ name: 'Profile', params: { id: post.user.id } }">
              {{ post.user.username }}
            </router-link>
          </div>
          <div class="text-sm text-gray-500">
            {{ formatDate(post.createdAt) }}
          </div>
        </div>
      </div>
      
      <!-- 帖子内容 -->
      <div class="mt-4">
        <p class="text-gray-800 text-lg">{{ post.content }}</p>
      </div>
      
      <!-- 帖子图片 -->
      <div v-if="post.imageUrl" class="mt-4">
        <img 
          :src="post.imageUrl" 
          alt="Post image" 
          class="w-full h-auto rounded-lg object-cover"
        >
      </div>
      
      <!-- 帖子互动区 -->
      <div class="mt-6 flex justify-between items-center">
        <div class="flex space-x-4">
          <button
            class="flex items-center text-gray-500 hover:text-red-500 transition"
            @click="toggleLike"
          >
            <i class="fas fa-heart" :class="{ 'text-red-500': isLiked }"></i>
            <span class="ml-1">{{ post.likesCount }}</span>
          </button>
          
          <button
            class="flex items-center text-gray-500 hover:text-blue-500 transition"
            @click="showCommentBox = true"
          >
            <i class="fas fa-comment"></i>
            <span class="ml-1">{{ post.commentsCount }}</span>
          </button>
        </div>
        
        <div class="flex space-x-4">
          <button class="text-gray-500 hover:text-blue-500 transition">
            <i class="fas fa-share-alt"></i>
          </button>
          <button class="text-gray-500 hover:text-gray-700 transition">
            <i class="fas fa-bookmark" :class="{ 'text-blue-500': isSaved }"></i>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 评论输入框 -->
    <div v-if="showCommentBox" class="p-4 border-t border-gray-100">
      <div class="flex space-x-3">
        <UserAvatar :user="currentUser" size="sm" />
        
        <div class="flex-1">
          <input
            v-model="commentText"
            type="text"
            placeholder="添加评论..."
            class="w-full border border-gray-300 rounded-full px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
          
          <div class="flex justify-end mt-2">
            <button
              class="bg-blue-500 hover:bg-blue-600 text-white text-sm font-medium py-1 px-3 rounded-md transition duration-300"
              @click="addComment"
              :disabled="!commentText.trim()"
            >
              发布
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 评论列表 -->
    <div v-if="post.comments && post.comments.length > 0" class="p-4">
      <h3 class="font-medium text-gray-900 mb-4">评论 ({{ post.commentsCount }})</h3>
      
      <div v-for="comment in post.comments" :key="comment.id" class="mb-4">
        <div class="flex space-x-3">
          <UserAvatar :user="comment.user" size="sm" />
          
          <div class="flex-1">
            <div class="bg-gray-100 rounded-lg p-3">
              <div class="font-medium text-gray-900 text-sm">
                {{ comment.user.username }}
              </div>
              <div class="text-gray-700 text-sm">
                {{ comment.content }}
              </div>
            </div>
            <div class="flex items-center mt-1 text-xs text-gray-500">
              <span>{{ formatDate(comment.createdAt) }}</span>
              <span class="mx-2">·</span>
              <button class="hover:text-blue-500">回复</button>
              <span class="mx-2">·</span>
              <button class="hover:text-blue-500">点赞 ({{ comment.likesCount || 0 }})</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { usePostStore } from '@/store/modules/post'
import UserAvatar from '@/components/user/UserAvatar.vue'
import { formatDistanceToNow } from 'date-fns'

export default {
  components: {
    UserAvatar
  },
  
  setup() {
    const route = useRoute()
    const router = useRouter()
    const authStore = useAuthStore()
    const postStore = usePostStore()
    
    const postId = computed(() => route.params.id)
    const post = computed(() => postStore.getPostById(postId.value) || {})
    const currentUser = computed(() => authStore.currentUser)
    
    const isLiked = computed(() => 
      post.value.likes?.some(like => like.userId === currentUser.value?.id)
    )
    
    const isSaved = ref(false) // 简化实现，实际应从状态管理获取
    const showCommentBox = ref(false)
    const commentText = ref('')
    
    // 格式化日期为相对时间（如"10分钟前"）
    const formatDate = (dateString) => {
      return formatDistanceToNow(new Date(dateString), { addSuffix: true })
    }
    
    // 页面加载时获取帖子详情
    onMounted(async () => {
      try {
        if (!post.value.id) {
          // 如果帖子不在store中，从API获取
          await postStore.fetchPostById(postId.value)
        }
      } catch (error) {
        console.error('Error fetching post:', error)
        router.push('/') // 出错时返回首页
      }
    })
    
    // 点赞/取消点赞
    const toggleLike = async () => {
      try {
        await postStore.toggleLike(postId.value)
      } catch (error) {
        console.error('Error toggling like:', error)
      }
    }
    
    // 添加评论
    const addComment = async () => {
      if (!commentText.value.trim()) return
      
      try {
        await postStore.addComment(postId.value, commentText.value)
        commentText.value = ''
        showCommentBox.value = false
      } catch (error) {
        console.error('Error adding comment:', error)
      }
    }
    
    return {
      post,
      currentUser,
      isLiked,
      isSaved,
      showCommentBox,
      commentText,
      formatDate,
      toggleLike,
      addComment
    }
  }
}
</script>